﻿using System;
using System.Collections.Generic;
using System.Linq;
using eAtlantida.Tools.Operations.GenerateOperations;

namespace eAtlantida.Tools.Operations
{
    public class CommandLine
    {
        public delegate void Message(string message, MessageType messageType);

        public event Message SendMessage;

        private void AttachEvents(Operation operation)
        {
            operation.SendMessage += (message, messageType) => SendMessage(message, messageType);
        }

        private readonly State state = new State();

        private string[] commandParameters { get; set; }
        private string commandText { get; set; }

        private readonly Dictionary<string, Operation> operations = new Dictionary<string, Operation>();

        public CommandLine()
        {
            var helpOperation = new HelpOperation();
            AttachEvents(helpOperation);
            operations.Add(HelpOperation.Name, helpOperation);

            var connectOperation = new ConnectOperation();
            AttachEvents(connectOperation);
            operations.Add(ConnectOperation.Name, connectOperation);

            var connectionOperation = new ConnectionOperation();
            AttachEvents(connectionOperation);
            operations.Add(ConnectionOperation.Name, connectionOperation);

            var generateOperation = new GenerateOperation();
            AttachEvents(generateOperation);
            operations.Add(GenerateOperation.Name, generateOperation);
        }

        public void ExecuteCommand(string command)
        {
            ParseCommand(command);

            if (operations.ContainsKey(commandText))
            {
                operations[commandText].Execute(state);
            }
            else
            {
                SendMessage("Unknown command! Type 'help' for showing all available commands.", MessageType.Warning);
            }
        }

        private void ParseCommand(string command)
        {
            commandParameters = new string[0];
            var splittedCommand = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (splittedCommand.Length > 0)
            {
                commandText = splittedCommand[0];
                if (splittedCommand.Length > 1)
                {
                    commandParameters = splittedCommand.Skip(1).ToArray();
                }
            }
            state.CommandParameters = commandParameters;
        }
    }
}